package utils

import (
	"fmt"
	"time"
)

type Duration int64

var (
	secondDuration time.Duration
	hourDuration   time.Duration
	dayDuration    time.Duration
)

func init() {
	secondDuration, _ = time.ParseDuration("1s")
	hourDuration, _ = time.ParseDuration("1h")
	dayDuration, _ = time.ParseDuration("1m")
}

func TimeOffsetSecond(offset int) time.Time {
	d := time.Duration(offset)
	return time.Now().Add(secondDuration * d)
}

func TimeOffsetHour(offset int) time.Time {
	d := time.Duration(offset)
	return time.Now().Add(hourDuration * d)
}

func TimeOffsetDay(offset int) time.Time {
	d := time.Duration(offset)
	return time.Now().Add(dayDuration * d)
}

const (
	TimeFmtDateSimple     = "20060102"
	TimeFmtDatePureSimple = "20060102150405"
	TimeFmtSimple         = "2006-01-02"
	TimeFmtNor            = "2006-01-02 15:04:05"
	TimeFmtNorMillis      = "2006-01-02 15:04:05.000"
)

// TimeNow 获取当前时间
// eg: 2006-01-02 15:04:05
func TimeNow() string {
	return time.Now().Format(TimeFmtNor)
}

// TimeFmt 获取当前时间的指定格式
func TimeFmt(t time.Time) string {
	return TimeFmt2(t, TimeFmtNor)
}

// TimeFmt2 获取当前时间的指定格式
func TimeFmt2(t time.Time, fmt string) string {
	if t.IsZero() {
		return ""
	}
	if fmt == "" {
		fmt = TimeFmtNor
	}
	return t.Format(fmt)
}

// TimeNowFmt 获取当前时间的指定格式
func TimeNowFmt(fmt string) string {
	if fmt == "" {
		fmt = TimeFmtNor
	}
	return TimeFmt2(time.Now(), fmt)
}

// TimeNowDateSimple 格式化时间为 20060102
func TimeNowDateSimple() string {
	return TimeNowFmt(TimeFmtDateSimple)
}

// TimeNowDatePureSimple 格式化时间为 20060102150405
func TimeNowDatePureSimple() string {
	return TimeNowFmt(TimeFmtDatePureSimple)
}

// NowMillis 获取当前时间的毫秒数
func TimeNowMillis() int64 {
	return time.Now().UnixMilli()
}

// TimeFormatDateSeparator 格式化时间为 2006-01-02
//
//	param	separator	自定义分隔符，默认为	-
func TimeFormatDateSeparator(separator string) string {
	if separator == "" {
		separator = "-"
	}
	format := fmt.Sprintf("2006%s01%s02", separator, separator)
	return time.Now().Format(format)
}

// TimeParseTimestampToPure 将时间戳转换为时间
func TimeParseTimestampToPure(timestamp int64) time.Time {
	t := time.UnixMilli(timestamp)
	return t
}
